//
//  SqBanLiViewController.m
//  FengyuanXS
//
//  Created by 王冬 on 2020/8/5.
//  Copyright © 2020 王冬. All rights reserved.
// 15012345678  诉求分发待处理页面

#import "SqBanLiDetailViewController.h"
#import "SelectImageView.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import "LeaderListController.h"
#import "TypeCell.h"
#import "SqFinshViewCell.h"
@interface SqBanLiDetailViewController ()<TZImagePickerControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *shenqLabel;
@property (weak, nonatomic) IBOutlet UILabel *bumenLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *typeLabel;
@property (weak, nonatomic) IBOutlet UILabel *contentLabel;
@property (nonatomic, strong) YMTextView *textView;
@property (weak, nonatomic) IBOutlet UIView *backView;
@property (weak, nonatomic) IBOutlet SelectImageView *selectImageView;
@property (weak, nonatomic) IBOutlet UIView *headView;

@property (nonatomic, strong) NSArray *photos;
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, strong) NSMutableArray *imageArray1;
@property (nonatomic, strong) NSMutableArray *nameArray;

@property (nonatomic, copy)NSString *nameStr;
@property (nonatomic, copy)NSString *userID;
@property (nonatomic, copy)NSString *status;
@property (nonatomic, copy)NSString *auth;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UIView *bohuiView;
@property (weak, nonatomic) IBOutlet UIView *shangbaoView;
@property (weak, nonatomic) IBOutlet UIView *banliView;
@property (weak, nonatomic) IBOutlet UILabel *pictorLabel;
@property (weak, nonatomic) IBOutlet UIView *imagesView;
@end

@implementation SqBanLiDetailViewController
-(NSMutableArray *)imageArray{
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}
-(NSMutableArray *)imageArray1{
    if (!_imageArray1) {
        _imageArray1 = [NSMutableArray array];
    }
    return _imageArray1;
}
-(NSMutableArray *)nameArray{
    if (!_nameArray) {
        _nameArray = [NSMutableArray array];
    }
    return _nameArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"诉求分发";
    self.nameLabel.text = [NSString stringWithFormat:@"%@提交的%@",self.model.appeal.real_name,self.model.appeal.type_name];
    self.shenqLabel.text = self.model.appeal.real_name;
    self.bumenLabel.text = self.model.appeal.section_name;
    self.timeLabel.text = [self ConvertStrToTime:self.model.appeal.create_time];
    self.typeLabel.text = self.model.appeal.type_name;
    self.contentLabel.text = self.model.appeal.content;
    
    self.textView=[[YMTextView alloc]init];
      [self.backView addSubview:self.textView];
      self.textView.maxNumb = 200;
      self.textView.placeholderColor = [UIColor grayColor];
      self.textView.textFont = [UIFont systemFontOfSize:15];
      self.textView.backgroundColor=[UIColor whiteColor];

      [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
          make.left.top.right.bottom.mas_equalTo(0);
      }];
      self.textView.placeholder = @"办理意见";
      self.textView.isFinishKeyboard = YES;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if (self.model.appeal.more.photos.count > 0) {
        self.headView.height = 300;
        self.pictorLabel.hidden = NO;
        self.imagesView.hidden = NO;
    }else{
        
        self.headView.height = 225;
    }
    if ([self.model.can_report isEqualToString:@"0"]) {
        self.shangbaoView.hidden = YES;
//        self.shangbaoView.width = 0;
//        self.banliView.width = kSCREEN_WIDTH/2;
//        self.bohuiView.width = kSCREEN_WIDTH/2;
    }else{
         self.shangbaoView.hidden = NO;
    }
    if ([self.model.can_reject isEqualToString:@"0"]) {
        self.bohuiView.hidden = YES;
    }else{
         self.bohuiView.hidden = NO; //流程4测试上报
    }
    
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
           [flow setScrollDirection:UICollectionViewScrollDirectionHorizontal];//竖直滑动
           flow.itemSize = CGSizeMake(70, 70);
       self.collectionView.delegate = self;
       self.collectionView.dataSource = self;
       self.collectionView.showsHorizontalScrollIndicator = NO;
       self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.collectionViewLayout = flow;
       [self.collectionView registerNib:[UINib nibWithNibName:@"TypeCell" bundle:nil] forCellWithReuseIdentifier:@"TypeCell1"];//注册cel
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SqFinshViewCell" bundle:nil] forCellReuseIdentifier:@"SqFinshViewCell6"];
    
    
    
    
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
//    return self.treeList.count;
    return self.model.appeal.more.photos.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TypeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TypeCell1" forIndexPath:indexPath];
    PhotosModel *model = self.model.appeal.more.photos[indexPath.row];
    
//    [cell.backImageView sd_setImageWithURL:[NSURL URLWithString:@"%@%@",BaseImgUrl,model.url]];
    
    NSString * str1 = @"\\";
   NSString  *imageUrl = [model.url stringByReplacingOccurrencesOfString:str1 withString:@"/"];
    [cell.backImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BaseImgUrl,imageUrl]]];
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//      PhotosModel *model = self.model.more.photos[indexPath.row];
    [self selectedIndex:indexPath.row withImageURLs:self.model.appeal.more.photos];
}

- (void)selectedIndex:(NSInteger)index withImageURLs:(NSArray *)urlsArray{
    NSMutableArray *datas = [NSMutableArray array];
 
    for (PhotosModel *model in urlsArray) {
        YBIBImageData *data = [YBIBImageData new];
        NSString * str1 = @"\\";
        NSString  *imageUrl = [model.url stringByReplacingOccurrencesOfString:str1 withString:@"/"];
        data.imageURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BaseImgUrl,imageUrl]];
        [datas addObject:data];
    }
    YBImageBrowser *browser = [YBImageBrowser new];
    browser.dataSourceArray = datas;
    browser.currentPage = index;
    [browser show];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
     FlowModel *model = self.model.flow[indexPath.row];
    if (model.more.photos > 0) {
        return 200;
    }else{
        
        return 115;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return  self.model.flow.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SqFinshViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SqFinshViewCell6" forIndexPath:indexPath];
    
    FlowModel *model = self.model.flow[indexPath.row];
    
    if (model.more.photos.count >0) {
        cell.imageLabel.hidden = NO;
        cell.selectImageView.hidden = NO;
    }else{
       cell.imageLabel.hidden = YES;
       cell.selectImageView.hidden = YES;
    }
    if ([model.auth isEqualToString:@"1"]) {
        cell.titleLabel.text = @"管理部门研判";
    }
    if ([model.auth isEqualToString:@"2"]) {
           cell.titleLabel.text = @"单位领导审批";
       }
    if ([model.auth isEqualToString:@"3"]) {
           cell.titleLabel.text = @"承办单位办理";
       }
    if ([model.auth isEqualToString:@"4"]) {
           cell.titleLabel.text = @"集团管理部门研判";
       }
    if ([model.auth isEqualToString:@"5"]) {
           cell.titleLabel.text = @"集团领导审批";
       }
    if ([model.auth isEqualToString:@"6"]) {
           cell.titleLabel.text = @"集团承办单位办理";
       }
    
    cell.bumenLabel.text = model.section_name;
    cell.nameLabel.text = model.real_name;
    cell.timeLabel.text = [self ConvertStrToTime:model.create_time];
    cell.contentLabel.text = model.content;
    cell.imageArray = model.more.photos;
    WS(weakSelf);
       cell.selectItem = ^(NSInteger index) {

    [weakSelf selectedIndex:index withImageURLs:model.more.photos];
           
       };
    
    return cell;
}



//时间戳变为格式时间
- (NSString *)ConvertStrToTime:(NSString *)timeStr{
    
    long long time=[timeStr longLongValue];
    //    如果服务器返回的是13位字符串，需要除以1000，否则显示不正确(13位其实代表的是毫秒，需要除以1000)
    //    long long time=[timeStr longLongValue] / 1000;
    
    NSDate *date = [[NSDate alloc]initWithTimeIntervalSince1970:time];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString*timeString=[formatter stringFromDate:date];
    
    return timeString;
    
}


- (IBAction)selectImageBtn:(UIButton *)sender {
    if(self.photos.count >=4){
              UIAlertView *aler  = [[UIAlertView alloc]initWithTitle:@"" message:@"最多可以选择4张哦" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
              [aler show];
          }
          TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:4 delegate:self];
          
          // 你可以通过block或者代理，来得到用户选择的照片.
       WS(weakSelf);
          [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray *photos, NSArray *assets,BOOL isSelectOriginalPhoto) {
              weakSelf.selectImageView.images = photos;
              weakSelf.photos = photos;
              __block NSMutableArray *tempArray = [NSMutableArray arrayWithArray:photos];
              weakSelf.selectImageView.deleteItem = ^(NSInteger index) {
                  [tempArray removeObjectAtIndex:index];
                  weakSelf.selectImageView.images = tempArray;
                  weakSelf.photos = tempArray;

              };
              [[ApiManager ShardInstance]upLoadImageimageArray:weakSelf.photos resultBlock:^(NSDictionary *data, NSError *error) {
                  [weakSelf.imageArray addObjectsFromArray:data[@"rs"]];
                  
                  for (int i = 0; i<weakSelf.imageArray.count; i++) {
                      [weakSelf.imageArray1 addObject:[NSString stringWithFormat:@"android/%@",weakSelf.imageArray[i]]];
                  }
                  
              }]; // 流程4测试上报办理
          }];
       
          [self presentViewController:imagePickerVc animated:YES completion:nil];
    
}


- (IBAction)banliBtn:(UIButton *)sender {
    for (int i =0; i< self.imageArray.count; i++) {
           
        [self.nameArray addObject:[NSString stringWithFormat:@"iosb%d",i]];
           
       }
    
    
    if ([[TokenManager getSection_main] isEqualToString:@"1"]){
        
        self.auth = @"1";
    }else if([[TokenManager getSection_main] isEqualToString:@"2"]){
        self.auth = @"4";
    }
    self.status = @"1";
    
    LeaderListController *testVC = [LeaderListController loadStroyboard:[LeaderListController new]];
    testVC.staff_id = self.model.appeal.staff_id;
    WS(weakSelf);
    testVC.leaderBlock = ^(NSString * _Nonnull name, NSString * _Nonnull userID) {
        weakSelf.nameStr = name;
        weakSelf.userID = userID;
        
        if (weakSelf.textView.textView.text.length <= 0) {
            [[ToastManager shardInstance]showToast:@"请输入内容"];
        }else{

           
            
            NSLog(@"%@===%@",self.auth,self.status);
            
             [[ApiManager ShardInstance]appealFlowPostAppeal_id:self.model.appeal.id user_id:[TokenManager getUserId] receive_id:self.userID  status:self.status content:self.textView.textView.text last_step:self.last_step photo_name:self.nameArray photo_urls:self.imageArray1 auth:self.auth resultBlock:^(NSDictionary *data, NSError *error) {
                    
                    BaseModel *model = [BaseModel mj_objectWithKeyValues:data];
                    if (model.code == 1) {
                        [weakSelf.navigationController popViewControllerAnimated:YES];
                    }else{
                        [[ToastManager shardInstance]showToast:model.msg];
                    }
                  
                    
                }];
   
        }
        
        
        
    
    };
           STPopupController *popupController = [[STPopupController alloc] initWithRootViewController:testVC];
           popupController.style = STPopupStyleFormSheet;
           popupController.transitionStyle = STPopupTransitionStyleFade;
           popupController.containerView.layer.cornerRadius = 5.0f;
           [popupController setNavigationBarHidden:YES];
           [popupController presentInViewController:self];
    
}
- (IBAction)bohuiBtn:(UIButton *)sender {
    
   
    
    if ([[TokenManager getSection_main] isEqualToString:@"1"]){

        self.auth = @"1";
        self.status = @"9";
    }else if([[TokenManager getSection_main] isEqualToString:@"2"]){
        self.auth = @"4";
        if ([self.model.appeal.is_report isEqualToString:@"0"]) {
            self.status = @"9";
        }else{
            self.status = @"5";
        }

    }
    
 
    
    
    for (int i =0; i< self.imageArray.count; i++) {
        
        [self.nameArray addObject:[NSString stringWithFormat:@"iosbo%d",i]];
        
    }
    if (self.textView.textView.text.length <= 0) {
            [[ToastManager shardInstance]showToast:@"请输入内容"];
    }else{
        WS(weakSelf);
        [[ApiManager ShardInstance]appealFlowPostAppeal_id:self.model.appeal.id user_id:[TokenManager getUserId] receive_id:@"0" status:self.status  content:self.textView.textView.text last_step:self.last_step photo_name:self.nameArray photo_urls:self.imageArray1 auth:self.auth resultBlock:^(NSDictionary *data, NSError *error) {
               
               BaseModel *model = [BaseModel mj_objectWithKeyValues:data];
               if (model.code == 1) {
                   [weakSelf.navigationController popViewControllerAnimated:YES];
               }else{
                   [[ToastManager shardInstance]showToast:model.msg];
               }
             
               
           }];
        
        
    }
    
    
    
}
- (IBAction)shangbBtn:(UIButton *)sender {
    
    
    for (int i =0; i< self.imageArray.count; i++) {
        
        [self.nameArray addObject:[NSString stringWithFormat:@"iossb%d",i]];
        
    }
    WS(weakSelf);
    
    if (self.textView.textView.text.length <= 0) {
         [[ToastManager shardInstance]showToast:@"请输入内容"];//
        return;
    }
    [[ApiManager ShardInstance]appealFlowPostAppeal_id:self.model.appeal.id user_id:[TokenManager getUserId] receive_id:@"0" status:@"2"  content:self.textView.textView.text last_step:self.last_step photo_name:self.nameArray photo_urls:self.imageArray1 auth:@"1" resultBlock:^(NSDictionary *data, NSError *error) {
        
        BaseModel *model = [BaseModel mj_objectWithKeyValues:data];
        if (model.code == 1) {
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }else{
            [[ToastManager shardInstance]showToast:model.msg];
        }
      
        
    }];
}


@end
